<template>
  <div class="app-container">
    <el-row v-show="!isInit">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>通义千问</span>
        </div>
        <div style="margin-bottom:50px;">
          <el-col :span="16" class="text-center">
            <router-link class="pan-btn blue-btn" to="/documentation/index">
              今天我能帮你做些什么呢？
            </router-link>
          </el-col>
        </div>
      </el-card>
    </el-row>
    <el-row v-show="isInit" style="margin-top: 30px;margin-left: 25%;margin-right: 25%;">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>通义千问</span>
        </div>
        <div ref="messageContainer" class="message-container">
          <!-- 系统消息 -->
          <div v-for="(message,index) in messagesList" :key="index" :class="message.role=='user'?'user-message':'system-message'" style="margin-top: 15px;">
            <div v-if="message.role === 'user'" class="avatar">
              <!-- 用户头像 -->
              <img src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/30/h/30">
            </div>
            <div class="message-content" :class="message.role">
              <!-- 时间戳 -->
              <div class="message-time">{{ message.time }}</div>
              <!-- 消息内容 -->
              <div class="message-text">
                <vue-markdown :source="message.content" />
              </div>
            </div>
            <div v-if="message.role === 'system'" class="avatar">
              <!-- 系统头像 -->
              <!--              <img src="system-avatar.jpg">-->
            </div>
          </div>

        </div>
      </el-card>
    </el-row>
    <el-row class="user-box">
      <el-col :span="24">
        <div class="input-container">
          <el-input v-model="message" placeholder="输入您想要了解的问题" style="flex-grow: 1;width: 100%;" />

          <el-button type="primary" style="margin-left: 20px;" @click="sendMessageStream">发送</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { chat, storeChatMessage } from '@/api/ai/ai'
import VueMarkdown from 'vue-markdown'
import messageUtil from '@/api/ai/messageUtil'
export default {
  name: 'IndexVue',
  components: {
    VueMarkdown
  },
  mixins: [messageUtil],
  data() {
    return {
      message: null,
      isInit: false,
      conversationId: 0,
      chatVo: {
        modelType: 'Ali',
        messages: [],
        conversationId: null
      },
      messageVo: {
        role: '',
        content: '',
        time: ''
      },
      messagesList: []

    }
  },
  beforeMount() {

  },
  updated() {

  },
  created() {
    const messageHistoryList = localStorage.getItem('messagesList')

    if (messageHistoryList) {
      if (messageHistoryList.length > 0) {
        console.log(messageHistoryList.length)
        this.messagesList = JSON.parse(messageHistoryList) || []
        this.isInit = true
      }
    }
  },
  mounted() {

  },
  destroyed() {

  },
  methods: {
    postMessageStore(systemMessageVo) {
      storeChatMessage(systemMessageVo, this.conversationId, this.chatVo.modelType).then(response => {})
    },
    sendMessageStream() {
      let number = 0
      const userMessageVo = this.createUserMessage(this.message)
      this.messagesList.push(userMessageVo)
      const eventSource = new EventSource('http://127.0.0.1:8080/market/chatStream?chatType=Ali&content=' + encodeURI(this.message) + '&conversationId=' + this.conversationId)
      eventSource.onopen = () => {
        console.log('SSE 连接已建立')
      }

      eventSource.onerror = (error) => {
        console.error('SSE 连接错误:', error)
        localStorage.setItem('messagesList', JSON.stringify(this.messagesList))
        const systemMessageVo = this.messagesList[this.messagesList.length - 1]
        systemMessageVo.conversationId = this.conversationId
        this.postMessageStore(systemMessageVo)
        eventSource.close()
      }

      eventSource.addEventListener('message', (event) => {
        const message = JSON.parse(event.data)
        this.isInit = true
        number = number + 1
        const systemMessageVo = this.createSystemMessage(message)
        this.conversationId = message.conversationId
        if (number > 1) {
          this.messagesList.pop()
        }
        this.messagesList.push(systemMessageVo)
        this.message = ''
        this.chatVo.messages = []

        // console.log(systemMessageVo)
        // this.messages.push(message);
      })
    },
    sendMessage() {
      this.messageVo.content = this.message
      this.messageVo.role = 'user'

      this.chatVo.messages.push(this.messageVo)

      if (this.conversationId > 0) {
        this.chatVo.conversationId = this.conversationId
      }
      const userMessageVo = this.createUserMessage(this.message)
      this.messagesList.push(userMessageVo)
      this.isInit = true
      chat(this.chatVo).then(response => {
        const systemMessageVo = this.createSystemMessage(response.data.content)
        this.conversationId = response.data.conversationId
        this.messagesList.push(systemMessageVo)
        this.message = ''
        this.chatVo.messages = []
        localStorage.setItem('messagesList', JSON.stringify(this.messagesList))
      })
    },
    // 处理滚动事件
    handleScroll() {
      // 获取消息容器元素
      const container = this.$refs.messageContainer
      // 判断是否出现垂直滚动条
      if (container.scrollHeight > container.clientHeight) {
        // 如果出现了垂直滚动条，则处理滚动条样式
        container.style.overflowY = 'auto'
      } else {
        // 如果没有出现垂直滚动条，则隐藏滚动条
        container.style.overflowY = 'hidden'
      }
    }
  }
}
</script>

<style scoped>
  body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
  }

  /* 设置 dialog 样式 */
  .dialog-box {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  /* 设置对话框消息容器样式 */
  .message-container {
    display: flex;
    flex-direction: column;
    gap: 10px;
    overflow-y: auto;
    max-height: 800px;
  }

  /* 设置系统消息样式 */
  .system-message {
    align-self: flex-start;
    background-color: #f0f0f0;
    border-radius: 5px;
    padding: 8px 12px;
    display: flex;
    align-items: center;
  }

  /* 设置用户消息样式 */
  .user-message {
    align-self: flex-end;
    background-color: #c3e88d;
    border-radius: 5px;
    padding: 8px 12px;
    display: flex;
    align-items: center;
  }

  .user-box {
    position: fixed;
    bottom: 50px;
    /*left: 50%;*/
    /*transform: translateX(-50%);*/
    width: 80%;
    padding: 10px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  .input-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  /* 消息时间样式 */
  .message-time {
    margin-bottom: 4px;
    font-size: 12px;
    color: #999;
  }

  /* 头像样式 */
  .avatar {
    margin-right: 8px;
  }

</style>
